package com.lr.app.application;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import com.ws.commons.interfac.Result;

public class MySessionContext {

	/**
	 * session超时时间（单位：秒）
	 */
	private final static long SESSION_TIMEOUT = 60*60;

	private static final Map<String, MySession> SESSION_CONTEXT = new HashMap<>();
	private static final Map<String, MySession> LOGIN_CONTEXT = new HashMap<>();

	/**
	 * 创建session
	 * 
	 * @return
	 */
	public static synchronized MySession createSession() {
		MySession mySession = new MySession();
		SESSION_CONTEXT.put(mySession.getId(), mySession);
		return mySession;
	}

	/**
	 * 获取session
	 * 
	 * @param sessionIdOrSubjectId
	 * @return
	 */
	public static MySession getSession(String sessionIdOrSubjectId) {
		MySession mySession = SESSION_CONTEXT.get(sessionIdOrSubjectId);
		if (mySession == null) {
			mySession = LOGIN_CONTEXT.get(sessionIdOrSubjectId);
		}
		return mySession;
	}

	/**
	 * 获取有效的session
	 * 
	 * @param sessionIdOrSubjectId
	 * @return
	 */
	public static MySession getValidSession(String sessionIdOrSubjectId) {
		MySession mySession = SESSION_CONTEXT.get(sessionIdOrSubjectId);
		if (mySession == null) {
			mySession = LOGIN_CONTEXT.get(sessionIdOrSubjectId);
			if (mySession == null) {
				return null;
			}
		}
		LocalDateTime now = LocalDateTime.now();
		int cmres = mySession.getLastActiveTime().plusSeconds(MySessionContext.SESSION_TIMEOUT).compareTo(now);
		if (cmres < 1) {
			logoutSession(mySession);
			return null;
		}
		return mySession;
	}

	/**
	 * 登录session
	 * 
	 * @param mySession
	 * @param sessionSubject
	 */
	public static synchronized void loginSession(MySession mySession, SessionSubject sessionSubject) {
		if (sessionSubject.getId() == null) {
			Result.sysError(SessionSubject.class.getName() + " id 不能为 null").throwIfError();
		}
		MySession srcMySession = SESSION_CONTEXT.get(mySession.getId());
		if (srcMySession == null) {
			srcMySession = LOGIN_CONTEXT.get(sessionSubject.getId());
			if (srcMySession != null) {
				srcMySession.active();
				return;
			} else {
				Result.warning("会话超时").throwIfNoSuccess();  
			}
		}
		LOGIN_CONTEXT.put(sessionSubject.getId(), srcMySession);
		mySession.login(sessionSubject);
	}

	/**
	 * 退出session
	 * 
	 * @param mySession
	 */
	public static synchronized void logoutSession(MySession mySession) {
		SESSION_CONTEXT.remove(mySession.getId());
		LOGIN_CONTEXT.remove(mySession.getLoginUser().getId());
	}

}
